
import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { setToken, getToken, removeToken, setTimeStamp } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken() || '',
  userinfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  // 取出获得用户信息接口的 数据
  setUserInfo(state, data) {
    state.userinfo = data
  },
  // 删除用户信息
  removeUserInfo(state) {
    state.userinfo = {}
  }
}
const actions = {
  // 登录
  async login(store, formData) {
    const data = await login(formData)
    // console.log(data)
    // 调用mutations的setToken函数
    store.commit('setToken', data)
    // 登录就记录时间戳
    setTimeStamp()
  },
  // 登出
  logout(store) {
    // 解决退出时 ，高权限换低权限登录后 残留权限问题的问题
    resetRouter()
    store.commit('removeToken')
    store.commit('removeUserInfo')
  },
  // 获取用户基本信息
  async getUserInfo(store) {
    const res = await getUserInfo()
    // console.log(res)
    // store.commit('setUserInfo', res)
    // 为了获取头像
    const baseinfo = await getUserDetailById(res.userId)
    console.log(baseinfo)
    const staffPhoto = { ...baseinfo, ...res }
    store.commit('setUserInfo', staffPhoto)
  }

}

export default {
  namespaced: true,
  actions,
  mutations,
  state
}
